#!/bin/bash
# version 5 zhong cheng @ 20210801. IF you have any suggestions please contact QQ:32589927 or E-mail: zhongcheng@whu.edu.cn 
if [ $# -lt 1 ]; then
    echo 'usage: -[a index of atom of interest, e.g. -a "15 11 12"] '
    echo '       -[v how many vectors to check, between 1-10, default is 5 ]'
    echo '       -[c if this option is set to all, then print all the internal coordination at end]'
    echo '       -[t temperature for boltzmann distribution in relexed scan job] logfile.log'
    echo '       -[m measure distance angle or torsion, e.g. -m "d2-3 a1-2-3 t1-2-3-4"] logfile.log'
    echo '       -[e extract structure, s2 for 2nd step of scan job, o3 for 3rd step of opt, '\
                   'r7 and f8 for 7th reverse and yth forward step of irc job, '\
                   'e for the final geom no matter what job, e.g. -e "s2 s4-8" will extract six structures from scan job and save as gjf] '
    echo '       -[K keywords for gjf] -[N %nproc for gjf] -[M %mem for gjf] options for extracted gjf file by -e'
    exit 1
fi
while getopts ":a:v:c:t:m:e:K:N:M:" opt
do
    case $opt in
        a) TA=$OPTARG;;
        v) NV=$OPTARG;;
        c) CD=$OPTARG;;
        m) MEASURE=$OPTARG;;
        e) EXTRACT=$OPTARG;;
        t) TEMPERATURE=$OPTARG;;
        K) KEYWORD=$OPTARG;;
        N) NPROC=$OPTARG;;
        M) MEM=$OPTARG;;
        ?) 
        echo 'usage: -[a index of atom of interest, e.g. -a "15 11 12"] '
        echo '       -[v how many vectors to check, between 1-10, default is 5 ]'
        echo '       -[c if this option is set to all, then print all the internal coordination at end]'
        echo '       -[t temperature for boltzmann distribution in relexed scan job] logfile.log'
        echo '       -[m measure distance angle or torsion, e.g. -m "d2-3 a1-2-3 t1-2-3-4"] logfile.log'
        echo '       -[e extract structure, s2 for 2nd step of scan job, o3 for 3rd step of opt, '\
                    'r7 and f8 for 7th reverse and yth forward step of irc job, '\
                    'e for the final geom no matter what job, e.g. -e "s2 s4" will extract two structures from scan job and save as gjf] '
        echo '       -[K keywords for gjf] -[N %nproc for gjf] -[M %mem for gjf] options for extracted gjf file by -e'
        exit 1;;
    esac
done

align_colunm() {
    awk '{if(NR==1) cols=NF}
    {if(NR==FNR && NF==cols) {for(i=1;i<=NF;i++) w[i] = (w[i] <= length($i) ? length($i) : w[i]);next}}
    {if(NF==cols) {for(i=1;i<=NF;i++) printf "%*s",w[i]+(i>1?2:0),$i;print ""}}' $1 $1  > TSM_TEMP
    mv TSM_TEMP $1
}

align_colunm_noheader() {
    awk '{if(NR==2) cols=NF}
    {if(NR==FNR && NF==cols && FNR!=1 ) {for(i=1;i<=NF;i++) w[i] = (w[i] <= length($i) ? length($i) : w[i]);next}}
    {if(NR!=FNR && FNR==1) {gsub(/^[ \t]+|[ \t]+$/, "");for(i=1;i<=length(w);i++) sum=sum+w[i]+(i>1?2:0);printf "%-*s\n",sum,$0}}
    {if(NF==cols && FNR!=1) {for(i=1;i<=NF;i++) printf "%*s",w[i]+(i>1?2:0),$i;print ""}}' $1 $1  > TSM_TEMP
    mv TSM_TEMP $1
}
measure_distance() {
    awk -v atoms=$2 'BEGIN{split(atoms,idx,"-")}
    {if(NR==idx[1]+1) {c1s=$4" "$5" "$6" ";split(c1s,c1," ")}
     if(NR==idx[2]+1) {c2s=$4" "$5" "$6" ";split(c2s,c2," ")}}
    END{s=0;for(i=1;i<=3;i++) s += (c1[i]-c2[i])^2;printf "%.5f",s^0.5}' $1
}
measure_angle() {
    awk -v atoms=$2 'BEGIN{split(atoms,idx,"-")}
    {if(NR==idx[1]+1) {c1s=$4" "$5" "$6" ";split(c1s,c1," ")}
    if(NR==idx[2]+1) {c2s=$4" "$5" "$6" ";split(c2s,c2," ")}
    if(NR==idx[3]+1) {c3s=$4" "$5" "$6" ";split(c3s,c3," ")}}
    END{for(i=1;i<=3;i++) {v1[i]=c1[i]-c2[i];v2[i]=c3[i]-c2[i]}
        dot=0;for(i=1;i<=3;i++) dot += v1[i]*v2[i]
        ncross=((v1[2]*v2[3]-v1[3]*v2[2])^2+(v1[3]*v2[1]-v1[1]*v2[3])^2+(v1[1]*v2[2]-v1[2]*v2[1])^2)^0.5
        angle=atan2(ncross,dot)*57.2957795 
        printf "%.3f",angle}' $1
}
measure_dihedral() {
    awk -v atoms=$2 'BEGIN{split(atoms,idx,"-")}
    {if(NR==idx[1]+1) {c1s=$4" "$5" "$6" ";split(c1s,c1," ")}
    if(NR==idx[2]+1) {c2s=$4" "$5" "$6" ";split(c2s,c2," ")}
    if(NR==idx[3]+1) {c3s=$4" "$5" "$6" ";split(c3s,c3," ")}
    if(NR==idx[4]+1) {c4s=$4" "$5" "$6" ";split(c4s,c4," ")}}
    END{for(i=1;i<=3;i++) {b0[i]=c1[i]-c2[i];b1[i]=c3[i]-c2[i];b2[i]=c4[i]-c3[i]}
    normb1 = (b1[1]^2 + b1[2]^2 + b1[3]^2)^0.5
    for(i=1;i<=3;i++) b1[i] = b1[i]/normb1
    dot10=0;for(i=1;i<=3;i++) dot10 += b0[i]*b1[i]
    dot21=0;for(i=1;i<=3;i++) dot21 += b2[i]*b1[i]
    for(i=1;i<=3;i++) {v[i]=b0[i]-dot10*b1[i];w[i]=b2[i]-dot21*b1[i]}
    dotvw=0;for(i=1;i<=3;i++) dotvw += v[i]*w[i]
    y=(b1[2]*v[3]-b1[3]*v[2])*w[1]+(b1[3]*v[1]-b1[1]*v[3])*w[2]+(b1[1]*v[2]-b1[2]*v[1])*w[3]
    angle=atan2(y,dotvw)*57.2957795
    printf "%.3f",angle}' $1
}

measure_all() {
    echo 0" "$2 > TSM_TEMP
    for i in TSM_GEOM/${1}*;do
        if [ -f $i ];then
            step=${i:19}
            mtype=${2:0:1}
            atoms=${2:1}
            case $mtype in 
                t)
                v=$(measure_dihedral $i $atoms)
                ;;
                d)
                v=$(measure_distance $i $atoms)
                ;;
                a)
                v=$(measure_angle $i $atoms)
                ;;
            esac
            echo $step" "$v  >> TSM_TEMP
        fi
    done
    echo -n "" > TSM_MEASURE
    sort -n TSM_TEMP | cut -d " " -f 2 >> TSM_MEASURE
}

convert2gjf() {
    if [ ! -f "$1" ];then
        echo "$1 dose not exist."
        return
    fi
    if [[ -z "$NPROC" ]];then
        NPROC=8
    fi
    if [[ -z "$MEM" ]];then
        MEM=8GB
    fi
    echo "%chk=${2/.gjf/}.chk" > $2
    echo "%nprocshared=$NPROC" >> $2
    echo "%mem=$MEM" >> $2
    echo "# $KEYWORD" >> $2
    echo "" >> $2
    echo "gjf generated by tsmonitor" >> $2
    echo "" >> $2
    echo "0 1" >> $2
    awk '{if (NF==6) printf("%-3d%15.6f%15.6f%15.6f\n",$2,$4,$5,$6)}' $1 >> $2
    echo "" >> $2
    echo "" >> $2
    echo "file $2 generated from $1"
}

extract_allgeom () {
    check_SO=$(grep -c "Standard orien" $1)
    if [ $check_SO -gt 0 ];then
        mkdir TSM_GEOM 2> /dev/null
        cd TSM_GEOM
        awk 'BEGIN{count=0;activate=0}
        /Standard orientation/{count=count+1;filename="TSM_GEOM_o"count;rc=0;activate=1}
        {if($0 ~ /--------/ && activate==1) rc=rc + 1}
        {if(rc > 3) activate==0}
        {if(rc==2) print $0 > filename}' ../$1
        cd ..
    else
        mkdir TSM_GEOM 2> /dev/null
        cd TSM_GEOM
        awk 'BEGIN{count=0;activate=0}
        /Input orientation/{count=count+1;filename="TSM_GEOM_o"count;rc=0;activate=1}
        {if($0 ~ /--------/ && activate==1) rc=rc + 1}
        {if(rc > 3) activate==0}
        {if(rc==2) print $0 > filename}' ../$1
        cd ..
    fi
}

extract_scangeom () {
    check_SO=$(grep -c "Standard orien" $1)
    filename=TSM_GEOM_s$2
    if [ $check_SO -gt 0 ];then
        mkdir TSM_GEOM 2> /dev/null
        cd TSM_GEOM
        awk 'BEGIN{activate=0;coords=""}
        /Standard orientation/{rc=0;activate=1;coords=""}
        {if($0 ~ /--------/ && activate==1) rc=rc + 1}
        {if(rc > 3) activate==0}
        {if(rc==2) coords=coords""$0"\n" }
        END{print coords}' ../$1 > $filename
        cd ..
    else
        mkdir TSM_GEOM 2> /dev/null
        cd TSM_GEOM
        awk 'BEGIN{activate=0;coords=""}
        /Input orientation/{rc=0;activate=1;coords=""}
        {if($0 ~ /--------/ && activate==1) rc=rc + 1}
        {if(rc > 3) activate==0}
        {if(rc==2) coords=coords""$0"\n" }
        END{print coords}' ../$1 > $filename
    fi
}

check_status () {
    Finfo=`grep 'Normal t' $1 | tail -n 1 `
    if [[ -n "$Finfo" ]];then
        echo $Finfo
    else
        Finfo=`grep 'Error t' $1`
        if [[ -n "$Finfo" ]];then
            echo $Finfo
        else
            echo "Unfinished job"
        fi
    fi
}
# parse EXTRACT
if [[ -n "$EXTRACT" ]];then
    NEW_EX=""
    for e in $EXTRACT;do
        if [[ "$e" =~ "-" ]];then
            head=${e:0:1}
            tail=${e:1}
            begin=${tail%-*}
            end=${tail#*-}
            for i in `seq $begin $end`;do
                NEW_EX=${NEW_EX}${head}${i}" "
            done
        else
            NEW_EX=${NEW_EX}${e}" "
        fi
    done
    EXTRACT=$NEW_EX
fi
shift $(($OPTIND - 1))
if [[ -z "$NV" ]];then
    NV=5
fi
if [[ -z "$TEMPERATURE" ]];then
    TEMPERATURE=298.15
fi
if [ ! -f "$1" ];then
    echo "file $1 not exist"
    exit
fi
INPF=$1
BASENAME=${1%.*}
awk 'BEGIN{count=0}/Initial command/{count=count+1;filename="TSM_LOG"count};{if(length(filename) >0) print $0 > filename}' $1
NSTEP=$(ls TSM_LOG? | wc -l)
echo "$NSTEP step job detected. Unit for energy is kCal/mol"
for INPF in TSM_LOG?;do
    if [ $NSTEP -gt 1 ];then
        echo "STEP ${INPF/TSM_LOG/}:"
    fi
    #detect scan job
    NOPT=$(grep -c 'Optimization completed'  $INPF)
    if [ "$NOPT" -gt 2 ];then
        echo "Multiple optimization detected"
        echo '' > TSM_SCANSTEP
        lin_no=$(awk '/Optimization completed/{print NR}' $INPF)
        finall=$(grep -c '' $INPF)
        lin_no=${lin_no}" "$finall
        lastl=1
        idx=1
        initEE=$(grep 'Total Ene' $INPF | tail -n 1 | awk '{print $NF}')
        if [ -z "$initEE" ];then
            printf "%4s\t%8s\t%-8s\n" "sn" "RE" "Boltzmann" > TSM_SCAN
        else
            printf "%4s\t%8s\t%8s\t%-8s\n" "sn" "RE" "REE" "Boltzmann" > TSM_SCAN
        fi
        for i in $lin_no;do
            idxstr=`printf "%03d" $idx`
            sed -n "$lastl,${i}p" $INPF >> TSM_TMPFILE_$idxstr
            lastl=$i
            if [ $idx -eq 1 ];then
                initE=$(grep 'SCF Done' TSM_TMPFILE_$idxstr | tail -n 1 | awk '{print $5}')
                initEE=$(grep 'Total Ene' TSM_TMPFILE_$idxstr | tail -n 1 | awk '{print $NF}')
            fi
            RelE=$(grep 'SCF Done' TSM_TMPFILE_$idxstr | tail -n 1 | awk -v ene="$initE" '{print ($5-ene)*627.51}')
            if [[ -n "$RelE" ]];then
                BOLTZ=$(echo "$RelE $TEMPERATURE" | awk '{printf "%.3e",2.71828182845904523536^(-1*$1*1000/1.98720425864083/$2)}') 
                if [[ -n "$initEE" ]];then
                    RelEE=$(grep 'Total Ene' TSM_TMPFILE_$idxstr | tail -n 1 | awk -v ene="$initEE" 'BEGIN{e=0}{e=($5-ene)*627.51;print e}')
                    BOLTZ=$(echo "scale=6;2.71828182845904523536 ^ (-1*$RelEE*1000/1.98720425864083/$TEMPERATURE)" | bc 2>/dev/null)
                    printf "%-4d\t%8.3f\t%8.3f\t%-8.3e\n" $idx $RelE $RelEE $BOLTZ >> TSM_SCAN
                else
                    printf "%-4d\t%8.3f\t%-8.3e\n" $idx $RelE $BOLTZ >> TSM_SCAN
                fi
            fi
            if [[ -n "$EXTRACT""$MEASURE" ]];then
                extract_scangeom TSM_TMPFILE_$idxstr $idx
            fi
            idx=$((idx+1))
        done
        if [[ -n "$EXTRACT" ]];then
            for e in $EXTRACT; do
                if [[ $e == "e" ]];then
                    INPFILE=$(ls -v TSM_GEOM/TSM_GEOM_* | tail -n 1)
                    OUTFILE=${BASENAME}_e.gjf
                else
                    OUTFILE=${BASENAME}_${e}.gjf
                    INPFILE=TSM_GEOM/TSM_GEOM_${e}
                fi
                convert2gjf $INPFILE $OUTFILE
            done
        fi
        if [[ -n  "$MEASURE" ]];then
            for m in $MEASURE; do
                measure_all TSM_GEOM_s $m
                paste TSM_SCAN TSM_MEASURE > TSM_TEMP
                mv TSM_TEMP TSM_SCAN
            done
        fi
        align_colunm TSM_SCAN 
        cat TSM_SCAN
        # check run status if Normal goto next stop, if not pass the unfinish part to INPF
        stat=`check_status $INPF`
        echo $stat
        if [[ "$stat" =~ "Normal t" ]];then
            continue
        fi
        INPF=TSM_TMPFILE_$idxstr
        echo "Following are the infor of the last step:"
    fi

#detect irc job
    NIRC=$(grep IRC-IRC-IRC $INPF  | wc -l)
    if [ "$NIRC" -gt 1 ];then
    echo "IRC job detected"
    awk 'BEGIN{f=0;r=0;ref=0;last=0;printf "%-6s%4s%10s%10s%10s%10s\n","sn","scf","RE","dE","MaxF*10","RMSF*10"}
    /in FORWARD/{f=1;gsub("Point Number","");pt=$1;r=0}
    /in REVERSE/{r=1;gsub("Point Number","");pt=$1;f=0}
    {if(f==1){
        if($0 ~ /SCF Done/){
            if(ref==0){ref=$5}
            if(last==0){last=$5}
            printf "F%03d  %4d%10.3f%10.3f",pt,$8,($5-ref)*627.5096,($5-last)*627.5096
            last=$5
            }
        if ($0 ~ /Forces:/){
            printf "%10.3f%10.3f\n",$4*10,$6*10
            }
        }
    }
    {if(r==1){
        if($0 ~ /SCF Done/){
        if(ref==0){ref=$5}
        if(last==0){last=$5}
        printf "R%03d  %4d%10.3f%10.3f",pt,$8,($5-ref)*627.5096,($5-last)*627.5096
        last=$5
        }
        if ($0 ~ /Forces:/){
            printf "%10.3f%10.3f\n",$4*10,$6*10
            }
        }
    }' $INPF > TSM_IRC
    echo -n "" > TSM_MIRC
    if [[ -n "$MEASURE""$EXTRACT" ]];then
        mkdir TSM_GEOM 2>/dev/null
        awk 'BEGIN{f=0;r=0}
        /in FORWARD/{f=1;gsub("Point Number","");pt=$1;r=0}
        /in REVERSE/{r=1;gsub("Point Number","");pt=$1;f=0}
        {if(f==1){
            if ($0 ~ /Cartesian Coordinates/){filename="TSM_GEOM/TSM_GEOM_f"pt;rc=0;activate=1}
                {if($0 ~ /--------/ && activate==1) rc=rc + 1}
                {if(rc > 3) activate==0}
                {if(rc==2) print $1"\t"$2"\t"0"\t"$3"\t"$4"\t"$5 > filename}
            }
        }
        {if(r==1){
            if ($0 ~ /Cartesian Coordinates/){filename="TSM_GEOM/TSM_GEOM_r"pt;rc=0;activate=1}
                {if($0 ~ /--------/ && activate==1) rc=rc + 1}
                {if(rc > 3) activate==0}
                {if(rc==2) print $1"\t"$2"\t"0"\t"$3"\t"$4"\t"$5 > filename}
            }
        }' $INPF 
        if [[ -n  "$MEASURE" ]];then
            for m in $MEASURE; do
                measure_all TSM_GEOM_f $m
                mv TSM_MEASURE TSM_MF
                measure_all TSM_GEOM_r $m
                sed '1d' TSM_MEASURE >> TSM_MF
                paste TSM_MIRC TSM_MF > TSM_TEMP
                mv TSM_TEMP TSM_MIRC
            done
        fi
        if [[ -n "EXTRACT" ]] ;then
            for e in $EXTRACT; do
                if [[ $e == "e" ]];then
                    INPFILE=$(ls -v TSM_GEOM/TSM_GEOM_* | tail -n 1)
                    OUTFILE=${BASENAME}_e.gjf
                else
                    OUTFILE=${BASENAME}_${e}.gjf
                    INPFILE=TSM_GEOM/TSM_GEOM_${e}
                fi
                convert2gjf $INPFILE $OUTFILE
            done
        fi
    fi
    paste TSM_IRC TSM_MIRC > TSM_TEMP
    mv TSM_TEMP TSM_IRC
    align_colunm TSM_IRC 
    cat TSM_IRC
    stat=`check_status $INPF`
    echo $stat
    # goto next step no matter what
    continue
    fi

    # extact goem for measure or output

    echo -n "" > TSM_ALLM
    if [[ -n "$EXTRACT""$MEASURE" ]];then
        echo "do geometry extraction or measurements...."
        # get geom
        extract_allgeom $INPF
        if [[ -n "EXTRACT" ]] ;then
            for e in $EXTRACT; do
                if [[ $e == "e" ]];then
                    INPFILE=$(ls -v TSM_GEOM/TSM_GEOM_* | tail -n 1)
                    OUTFILE=${BASENAME}_e.gjf
                else
                    OUTFILE=${BASENAME}_${e}.gjf
                    INPFILE=TSM_GEOM/TSM_GEOM_${e}
                fi
                convert2gjf $INPFILE $OUTFILE
            done
        fi
    # measure
        if [[ -n  "$MEASURE" ]];then
            for m in $MEASURE; do
                measure_all TSM_GEOM_o $m
                paste TSM_ALLM TSM_MEASURE > TSM_TEMP
                mv TSM_TEMP TSM_ALLM
            done
        fi
    fi

    echo "extracting energy and convergence info..."
# get scf energy and line_no for SCF Done
    line_no=`awk 'BEGIN{i=1}
                  {if($0 ~ /SCF Done/) {printf "%f\n",$5 > "TSM_SCFE";line_no[i]=NR;i++}}
                  END{line_no[i]=NR;for (no in line_no) print line_no[no]}' $INPF`
    initE=$(cat TSM_SCFE | head -n 1)
    relativeE=$(cat TSM_SCFE | awk -v ene="$initE" 'BEGIN{e=0}{de=($0-ene)*627.51-e;e=($0-ene)*627.51;printf "%10.3f%10.3f",e,de}')
    nscf=$(awk '{if($0 ~/SCF Done/) print $8}' $INPF)
    printf "%10s%10s\n" "RE" "dE" > TSM_TMP
    printf "%10.3f%10.3f\n" $relativeE >> TSM_TMP
    printf "%s\n" "scf" > TSM_SCF
    printf "%d\n" $nscf >> TSM_SCF
    paste TSM_TMP TSM_SCF > TSM_TMP2
    awk 'BEGIN{i=1}/.*/{if(NR==1) printf("sn%-10s\n",$0); else printf("%-4d%s\n",i,$0,i++)}' TSM_TMP2 > TSM_GE

# get excited state energy and generate TSM_ENERGY file
    startl=1
    echo -n "" > TSM_EE
    echo -n "" > TSM_EXCE
    for no in $line_no;do
        sed -n "$startl,$no p" $INPF | grep 'Total Ene' | awk '{print $NF}' >> TSM_EXCE
        startl=$no
    done
    initEE=$(cat TSM_EXCE | head -n 1)
    if [[ -n "$initEE" ]];then
        relativeEE=$(cat TSM_EXCE | awk -v ene="$initEE" 'BEGIN{e=0}{e=($0-ene)*627.51;print e}')
        printf "%-8s\n" "EE" > TSM_EE
        printf "%-8.3f\n" $relativeEE >> TSM_EE
        printf "%-8s\n" "nm" > TSM_nm
        paste TSM_SCFE TSM_EXCE | awk '{printf "%-8.2f\n",45.5640/($2-$1)}' >> TSM_nm
        paste TSM_GE TSM_EE TSM_nm > TSM_ENERGY
    else
        cp TSM_GE TSM_ENERGY
    fi

# get convergence information and generate TSM_CONV
    printf "%-6s\t%-6s\t%-6s\t%-6s\n" MF RF MD RD > TSM_CONV
    conv=$(awk '/Threshold/{getline
        MF=$3/$4
        getline
        RF=$3/$4
        getline
        MD=$3/$4
        getline
        RD=$3/$4
        printf("%-6.2f\t%-6.2f\t%-6.2f\t%-6.2f\n",MF,RF,MD,RD)}' $INPF)
    if [[ -z "$conv" ]];then
        conv=$(printf "%-6s\t%-6s\t%-6s\t%-6s\n" NA NA NA NA)
    fi
    echo "$conv" >> TSM_CONV
    if [ $(grep -c "Input orientation" $INPF) -eq $(cat TSM_CONV | wc -l) ];then
        conv=$(printf "%-6s\t%-6s\t%-6s\t%-6s\n" NA NA NA NA)
        echo "$conv" >> TSM_CONV
    fi
    paste TSM_ENERGY TSM_ALLM TSM_CONV > TSM_LEFT
    align_colunm TSM_LEFT
# get CI energy

    echo "extracting eigenvalues and eigenvectors...."
    # get first four eigenvalues
    eigenV=$(awk 'BEGIN{ITUFLAG=0}
    {if($0 ~/ITU/){ITUFLAG=1;count=0}
    if($0 ~ /Eigenvalues/ && ITUFLAG==1 ) {print $0;ITUFLAG=0} else count=count+1;if(count>3 && ITUFLAG==1) {print "0 0 0 0 0 0";ITUFLAG=0}}' $INPF | awk '{if(NF>5) print $3*100" "$4*100" "$5*100" "$6*100"\n";else print "0 0 0 0\n"}')
    # awk 'BEGIN{ITUFLAG=0};{if($0 ~/ITU/){ITUFLAG=1;count=0};if($0 ~ /Eigenvalues/ && ITUFLAG==1 ) {print $0;ITUFLAG=0} else count=count+1;if(count>3 && ITUFLAG==1) {print "0 0 0 0 0 0";ITUFLAG=0}}' DDC.log | awk '{if(NF>5) print $3*100" "$4*100" "$5*100" "$6*100"\n"}'
    printf "%27s\n" "Eigenvalue X 100" > TSM_EIGENV
    printf "%6.2f %6.2f %6.2f %6.2f\n" $eigenV >> TSM_EIGENV
    align_colunm_noheader TSM_EIGENV
    # get eigen vectors
    startl=1
    echo "Eigenvectors" > TSM_EIGENVCT1
    echo " " > TSM_EIGENVCT2
    for no in $line_no;do
        sed -n "$startl,$no p" $INPF | sed -nr '/Eigenvectors/{n;p}' | awk '{printf "%4s %4s %4s %4s %4s\n", $1, $2, $3, $4, $5}' | tail -n 1 >> TSM_EIGENVCT1
        sed -n "$startl,$no p" $INPF | sed -nr '/Eigenvectors/{n;n;n;p}' | awk '{printf "%4s %4s %4s %4s %4s\n", $1, $2, $3, $4, $5}' | tail -n 1 >> TSM_EIGENVCT2
        startl=$no
    done
    line=$(grep -c "" TSM_EIGENVCT1)
    if [ $line -le 1 ];then
        echo "Eigenvectors not found in the log file"
        paste  -d "~" TSM_LEFT TSM_EIGENV | sed 's/~/  /g' | cut -c 1-$(tput cols)
    else
        declare -A IC  #dictionary map internal coord label to atom index
        for i in `seq $NV`;do
            if [ $i -le 5 ];then
                awk -v c="$i" '{if(NR > 1) print $c}' TSM_EIGENVCT1 > TSM_V$i
            else
                awk -v c="$i" '{if(NR > 1) print $(c-5)}' TSM_EIGENVCT2 > TSM_V$i
            fi
            while read line; do 
                if [[ -z "${IC[$line]}" ]];then
                    IC[$line]=$(grep "! "$line" " $INPF |head -n 1 | awk '{print $3}' | sed  "s/[)(,A-Z]/ /g")
                fi
                ATOMS="${IC[$line]}"
                ALIST=""
                for atom in $TA;do
                    if [[ $ATOMS == *" $atom "* ]];then
                        ALIST=${ALIST}${atom}","
                    fi
                done
                if [[ -n "$ALIST" ]];then
                    ALIST="-"${ALIST%,}
                fi
                echo $ALIST
            done < TSM_V$i > TSM_A$i
            paste -d "" TSM_V$i TSM_A$i > TSM_AV$i
        done
        paste TSM_AV* | column -s $'\t' -t > TSM_ALLAV
        sed -i '1i\Eigenvectors' TSM_ALLAV
        paste -d "~" TSM_LEFT TSM_EIGENV TSM_ALLAV | sed 's/~/  /g' | cut -c 1-$(tput cols)
        if [[ -z "$CD" ]];then
            v1=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==1){print $1}')
            v2=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==1){print $2}')
            v3=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==1){print $3}')
            v4=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==1){print $4}')
            v5=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==1){print $5}')
            v6=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==3){print $1}')
            v7=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==3){print $2}')
            v8=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==3){print $3}')
            v9=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==3){print $4}')
            v10=$(grep -A 4 "Eigenvectors" $INPF | tail -n 4 | awk '(NR==3){print $5}')
            allv=($v1 $v2 $v3 $v4 $v5 $v6 $v7 $v8 $v9 $v10)
            for i in `seq 0 $((NV-1))`;do
                vl=${allv[$i]} 
                printf "%-5s" $vl":"
                echo ${IC[$vl]}
            done
        else
            for ic in "${!IC[@]}";do echo "$ic: ${IC[$ic]}";done
        fi
    fi
    check_status $INPF
done
rm -r TSM_*
